package com.bee.beemanage.system.aspect.filters;

import com.alibaba.fastjson.JSON;
import com.bee.beemanage.system.common.exceptions.VerifyCodeException;
import com.bee.beemanage.system.common.utils.IpUtil;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 */
@Component
public class VerifyCodeFilter extends OncePerRequestFilter {
    @Resource
    RedisUtils redisUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //非登录请求不校验验证码
        if(!"/admin/login".equals(request.getRequestURI())){
            filterChain.doFilter(request,response);
        } else {
            Result result;
            try {
                String verifyCode = request.getParameter("verifyCode");
                if(null==verifyCode){
                    throw new VerifyCodeException();
                }
                String realIp = IpUtil.getIpAddr(request);
                String checkCode = (String) redisUtils.get("VerifyCode:" + realIp);
                //输入的验证码和缓存里的一致，校验通过
                if(verifyCode.equals(checkCode)){
                    filterChain.doFilter(request, response);
                }else{
                    throw new VerifyCodeException();
                }
            }catch (VerifyCodeException e) {
                result = ResultTool.fail(ResultCode.VERIFY_CODE_ERROR);
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(result));
            }
        }
    }
}
